﻿using Com.Lancetinc.Evs.Data.Domain;

namespace Com.Lancetinc.Evs.Data.Repository
{
    public class ConfigRepository : CrudRepository<TblConfig>
    {
        public ConfigRepository()
            : base("Name")
        {
        }

        public TblConfig FindByName(string name)
        {
            return ExecuteWithoutTrans(cmd => FindByKey(cmd, name));
        }

        public int GetDbVersion()
        {
            var row = FindByName("db_version");
            if (row == null)
                return 0;
            if (int.TryParse(row.Value, out var v))
            {
                return v;
            }

            return 0;
        }

        public void Save(TblConfig config)
        {
            lock (config)
            {
                ExecuteWithTrans(cmd =>
                {
                    if (UpdateByKey(cmd, config) == 0)
                    {
                        Insert(cmd, config);
                    }

                    return 1;
                });
            }
        }
    }
}